tg-me.com/cpluspluc/1034
Create:
Last Update:
Last Update:
🔓Что выведет следующий код?
#include <iostream>
using namespace std;
class Base {
public:
Base() {
cout << "Base constructor: ";
call();
}
virtual void call() { cout << "Base::call\n"; }
};
class Derived : public Base {
int x = init();
int init() {
cout << "Derived::init\n";
return 42;
}
public:
Derived() {
cout << "Derived constructor\n";
}
void call() override {
cout << "Derived::call, x = " << x << "\n";
}
};
int main() {
Derived d;
return 0;
}
🔢Варианты ответа:
A)
Derived::init
Derived constructor
B)
Derived::init
Derived constructor
C)
Base constructor: Derived::call, x = 42
Derived constructor
D)
Derived::call, x = <undefined>
Derived::init
Derived constructor
✅
💡Почему?
В момент вызова конструктора Base, объект ещё не стал Derived. Виртуальная функция вызывается в контексте Base.
BY C++ Academy
Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283
Share with your friend now:
tg-me.com/cpluspluc/1034